// 导入axios 和 qs 插件
import axios from 'axios'
import qs from 'qs'
import { baseURL } from './env'

// // 配置全局公共域名
// const baseURL = 'https://elm.cangdu.org'

// 创建axios实例
const request = axios.create({
  baseURL, // 赋值公共域名
  timeout: 10000 // 设置延迟时间（单位：毫秒）
})

// 拦截request的发送请求和响应请求，并做一定的配置
axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    return config
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// Add a response interceptor
axios.interceptors.response.use(
  function(response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response
  },
  function(error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error)
  }
)

request.get = function(url, data, option = {}) {
  // 返回一个promise，实现异步处理
  return new Promise(function(resolve, reject) {
    request({
      url: url,
      method: 'GET',
      data,
      ...option,
      headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', ...option.headers }
    })
      .then(res => resolve(res))
      .catch(err => reject(err))
  })
}

// 给axios实例对象request添加postURL方法
request.post = function(url, data, option = {}) {
  // 返回一个promise，实现异步处理
  return new Promise(function(resolve, reject) {
    request({
      url: url,
      method: 'POST',
      data: qs.stringify(data),
      ...option,
      headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', ...option.headers }
    })
      .then(res => resolve(res))
      .catch(err => reject(err))
  })
}

// 给axios实例对象request添加postURL方法
request.delete = function(url, data, option = {}) {
  // 返回一个promise，实现异步处理
  return new Promise(function(resolve, reject) {
    request({
      url: url,
      method: 'delete',
      data,
      ...option,
      headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', ...option.headers }
    })
      .then(res => resolve(res))
      .catch(err => reject(err))
  })
}
// 导出request
export default request
